package com.karl.mytask_2.activity;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.karl.mytask_2.R;
import com.karl.mytask_2.bean.MyUser;
import com.karl.mytask_2.tools.BaseActivity;
import com.karl.mytask_2.tools.SelectPicPopupWindow;

import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

/**
 * Created by Karl on 2016/5/22.
 */
public class PersonalInfoActivity extends BaseActivity implements View.OnClickListener {
    private ImageButton mBack;
    private TextView mTitle;

    private TextView mName,mSignature,mPhone,mEmail;
    private LinearLayout mNameBtn,mSignatureBtn,mPhoneBtn,mEmailBtn,mImageBtn;
    private ImageView mImage;

    private SelectPicPopupWindow mPop;
    //图像
    private ImageOptions mImageOptions2 = new ImageOptions.Builder().setAutoRotate(true).setCircular(true)
            .setFadeIn(true).setSize(100,100).setLoadingDrawableId(R.mipmap.ic_launcher).build();
    public String  mIconUrl = "http://cdnq.duitang.com/uploads/item/201412/27/20141227140012_BV2Bu.jpeg";

    //编号
    public static final int TAKE_PHOTO = 1;
    public static final int CROP_PHOTO =2;
    public static final int CHOOSE_PHOTO =3;
    public static final int UPDATE_SIGNATURE=4;
    public static final int UPDATE_NICKNAME=5;

    private String name,signature;

    //本地选择图片
    private Uri mImageUri;
    private  String path;//作为返回的全局图片地址变量



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.personal_info);

        initView();
        initEvent();

    }
    private void initView(){
        mBack = (ImageButton) findViewById(R.id.tool_bar2_back);
        mTitle = (TextView) findViewById(R.id.tool_bar2_title);

        mName = (TextView) findViewById(R.id.user_info_name);
        mSignature = (TextView) findViewById(R.id.user_info_signature);
        mPhone = (TextView) findViewById(R.id.user_info_phone);
        mEmail = (TextView) findViewById(R.id.user_info_email);

        mNameBtn = (LinearLayout) findViewById(R.id.user_info_name_ll);
        mSignatureBtn = (LinearLayout) findViewById(R.id.user_info_signature_ll);
        mPhoneBtn = (LinearLayout) findViewById(R.id.user_info_phone_ll);
        mEmailBtn = (LinearLayout) findViewById(R.id.user_info_email_ll);

        mImage = (ImageView) findViewById(R.id.user_info_icon);
        mImageBtn = (LinearLayout) findViewById(R.id.user_info_img_ll);

    }
    private void initEvent(){
        //设置监听事件
        mNameBtn.setOnClickListener(this);
        mSignatureBtn.setOnClickListener(this);
        mImageBtn.setOnClickListener(this);
//        mPhoneBtn.setOnClickListener();

        //设置ToolBar

        mTitle.setText("个人信息");
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PersonalInfoActivity.this.finish();
            }
        });

        //获取用户信息
        showPersonalInfo();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.user_info_img_ll:
                mPop = new SelectPicPopupWindow(PersonalInfoActivity.this,picPicker);
                mPop.showAtLocation(this.findViewById(R.id.personal_info), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            case R.id.user_info_name_ll:
                Intent intentNickName = new Intent();
                intentNickName.putExtra("name",name);
                intentNickName.setClass(PersonalInfoActivity.this, Info_NickName.class);
                startActivityForResult(intentNickName, UPDATE_NICKNAME);
                break;
            case R.id.user_info_signature_ll:
                Intent intentS = new Intent();
                intentS.putExtra("signature",signature);
                intentS.setClass(PersonalInfoActivity.this, Info_Signature.class);
                startActivityForResult(intentS, UPDATE_SIGNATURE);
                break;
        }
    }

    /**
     * 点击选择更换头像方式选择
     */
    private View.OnClickListener picPicker = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mPop.dismiss();
            switch (v.getId()){
                case R.id.btn_take_photo:
                    //创建File对象，用于存储拍照后的图片
                    File outputImage = new File(Environment.getExternalStorageDirectory(),"icon.jpg");
                    try{
                        if (outputImage.exists()){
                            outputImage.delete();
                        }
                        outputImage.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mImageUri = Uri.fromFile(outputImage);
                    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT,mImageUri);
                    startActivityForResult(intent,TAKE_PHOTO);
                    break;
                case R.id.btn_pick_photo:
                    //从相册选择
                    Intent intent2 = new Intent("android.intent.action.GET_CONTENT");
                    intent2.setType("image/*");
                    startActivityForResult(intent2, CHOOSE_PHOTO);
                    break;
            }
        }
    };
    /**
     *返回数据操作
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case UPDATE_NICKNAME:
                //保存成功
                if (resultCode == RESULT_OK){
                    updateInfo(1);
                }
                break;
            case UPDATE_SIGNATURE:
                if (resultCode == RESULT_OK){
                    updateInfo(2);
                }
                break;
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK){
                    Intent intent = new Intent("com.android.camera.action.CROP");
                    intent.setDataAndType(mImageUri,"image/*");
                    intent.putExtra("scale", true);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT,mImageUri);
                    startActivityForResult(intent,CROP_PHOTO);//启动裁剪程序
                }
                break;
            case CROP_PHOTO:
                if (resultCode == RESULT_OK){
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mImageUri));
                        path = mImageUri.getPath();
//                        mImage.setImageBitmap(bitmap);//这里显示图片
                        uploadImage(path);


                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK){
                    //判断系统版本以及型号
                    if (Build.VERSION.SDK_INT >= 19){
                        //4.4及以上系统使用这个方法处理图片
                        handleImageOnKitKat(data);
                    }else {
                        //4.4以下系统使用这个方法处理图片
                        handleImageBeforeKitKat(data);
                    }
                    uploadImage(path);
                }
                break;
            default:
                break;
        }

    }

    /**
     * 该页面即查询用户信息并显示
     */
    private void showPersonalInfo(){
        BmobQuery<MyUser> queryInfo = new BmobQuery<>();
        MyUser user = BmobUser.getCurrentUser(this,MyUser.class);
        queryInfo.getObject(this, user.getObjectId(), new GetListener<MyUser>() {
            @Override
            public void onSuccess(MyUser myUser) {
                name = myUser.getNickName();
                signature = myUser.getSignature();

                mName.setText(myUser.getNickName());
                mEmail.setText(myUser.getEmail());
                mPhone.setText(myUser.getMobilePhoneNumber());
                if (!(signature == null)) {
                    mSignature.setText(myUser.getSignature());
                }else {
                    mSignature.setText("快去说点什么吧！");
                }
                if (myUser.getIcon() == null) {
                    x.image().bind(mImage, mIconUrl, mImageOptions2);
                } else {
                    x.image().bind(mImage, myUser.getIcon(), mImageOptions2);
                }
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(PersonalInfoActivity.this, "获取用户信息失败！", Toast.LENGTH_SHORT).show();
            }
        });
    }
    /**
     * 根据返回选择来判断显示哪个
     */
    private void updateInfo(int i){
        switch (i){
            case 1:{
                BmobQuery<MyUser> queryInfo = new BmobQuery<>();
                MyUser user = BmobUser.getCurrentUser(this,MyUser.class);
                queryInfo.getObject(this, user.getObjectId(), new GetListener<MyUser>() {
                    @Override
                    public void onSuccess(MyUser myUser) {
                        mName.setText(myUser.getNickName());
                    }

                    @Override
                    public void onFailure(int i, String s) {
                        Toast.makeText(PersonalInfoActivity.this, "获取用户信息失败！", Toast.LENGTH_SHORT).show();
                    }
                });
            }
                break;
            case 2:{
                BmobQuery<MyUser> queryInfo = new BmobQuery<>();
                MyUser user = BmobUser.getCurrentUser(this,MyUser.class);
                queryInfo.getObject(this, user.getObjectId(), new GetListener<MyUser>() {
                    @Override
                    public void onSuccess(MyUser myUser) {

                        if (!(signature == null)) {
                            mSignature.setText(myUser.getSignature());
                        }else {
                            mSignature.setText("快去说点什么吧！");
                        }
                    }

                    @Override
                    public void onFailure(int i, String s) {
                        Toast.makeText(PersonalInfoActivity.this, "获取用户信息失败！", Toast.LENGTH_SHORT).show();
                    }
                });
            }
                break;
        }
    }

    /**
     * 选取相册图片或者照片的实现方法
     */
    @TargetApi(19)
    private void handleImageOnKitKat(Intent data){
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)){
            //如果document类型是Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID+"="+id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId)
                );
                imagePath = getImagePath(contentUri,null);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            //如果不是document类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri,null);
        }
        path = imagePath;
    }
    private void handleImageBeforeKitKat(Intent data){
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        path = imagePath;
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过Uri和Selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null){
            if (cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return  path;
    }

    /**
     * 上传头像的方法,成功后返回一个图片Uri地址，并存入User表中
     */
    private void uploadImage(String path){
        final BmobFile bmobFile = new BmobFile(new File(path));
        bmobFile.uploadblock(getApplicationContext(), new UploadFileListener() {
            @Override
            public void onSuccess() {
                String uri = bmobFile.getFileUrl(getApplicationContext());
                updateImgInfo(uri);
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(PersonalInfoActivity.this, "上传文件失败！", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void updateImgInfo(final String path){
        MyUser myUser = BmobUser.getCurrentUser(this,MyUser.class);
        MyUser nUser = new MyUser();
        nUser.setIcon(path);
        nUser.update(this,myUser.getObjectId() , new UpdateListener() {
            @Override
            public void onSuccess() {
                x.image().bind(mImage, path, mImageOptions2);//显示头像
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(PersonalInfoActivity.this, "上传头像失败!", Toast.LENGTH_SHORT).show();
            }
        });
    }

}
